<script lang="ts" setup>
// import HelloWorld from '@/components/HelloWorld.vue';
import { ref } from 'vue';
import { Field, Button } from 'vant';

const inputValue = ref('');
const message = ref('');
const isLoading = ref(false);
const version = ref(browser.runtime.getManifest().version);

// 加载已保存的URL
onMounted(async () => {
  const result = await browser.storage.sync.get(['chatbotUrl']) as { chatbotUrl?: string };
  if (result.chatbotUrl) {
    inputValue.value = result.chatbotUrl;
    message.value = '已配置聊天机器人URL: ' + result.chatbotUrl;
  }
});

const checkDifyUrl = async () => {
  try {
    const result = await chrome.storage.sync.get('chatbotUrl');
    if (!result.chatbotUrl) {
      message.value = '请配置聊天机器人URL';
      return false;
    }
    return result.chatbotUrl;
  } catch (error) {
    console.error('检查存储失败:', error);
    return false;
  }
};

const fetchDifyResponse = async (query: string) => {
  const difyUrl = await checkDifyUrl();
  if (!difyUrl) return;
  
  isLoading.value = true;
  try {
    const response = await fetch(`${difyUrl}/api/v1/completion-messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: query,
        response_mode: 'blocking'
      })
    });
    const data = await response.json();
    message.value = data.answer || data.message;
  } catch (error) {
    console.error('请求dify失败:', error);
    message.value = '请求智能体机器人失败';
  } finally {
    isLoading.value = false;
  }
};

const isValidUrl = (url: string) => {
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
};

const handleClick = async () => {
  if (!inputValue.value) {
    alert('请输入URL地址');
    return;
  }
  
  if (!isValidUrl(inputValue.value)) {
    alert('URL格式不正确，请检查后重试');
    return;
  }

  try {
    await browser.storage.sync.set({ chatbotUrl: inputValue.value });
    console.log('Chatbot URL saved:', inputValue.value);
    alert('聊天机器人URL保存成功!');
  } catch (error) {
    console.error('保存失败:', error);
    alert('保存失败，请重试');
  }
};

// 调试用 - 添加检查存储的按钮
const checkStorage = async () => {
  const storage = await browser.storage.sync.get();
  console.log('Current storage:', storage);
  alert(`当前存储的URL: ${storage.chatbotUrl || '无'}`);
};
</script>

<template>
  <div class="popup-container">
    <h2 class="title">聊天机器人配置</h2>
    
    <div class="form-group">
      <Field 
        v-model="inputValue" 
        label="提示词连接" 
        placeholder="请输入提示词的URL"
        class="url-input"
      />
      <div class="button-group">
        <Button 
          type="primary" 
          @click="handleClick"
          class="save-btn"
        >
          保存配置
        </Button>
        <Button 
          type="default" 
          @click="checkStorage"
          class="check-btn"
        >
          检查配置
        </Button>
      </div>
    </div>

    <div v-if="message" class="message">{{ message }}</div>
    <div v-if="isLoading" class="loading">正在获取回复...</div>
    
    <div class="footer">
      <div class="version">版本: {{ version }}</div>
    </div>
  </div>
</template>

<style scoped>
.popup-container {
  padding: 16px;
  width: 300px;
  min-height: 200px;
  display: flex;
  flex-direction: column;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

.url-input {
  margin-bottom: 15px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.save-btn {
  flex: 1;
}

.check-btn {
  flex: 1;
}

.message {
  margin-top: 10px;
  padding: 8px;
  background: #f0f9eb;
  color: #67c23a;
  border-radius: 4px;
  font-size: 14px;
}

.loading {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.footer {
  margin-top: auto;
  text-align: center;
}

.version {
  font-size: 12px;
  color: #909399;
}
</style>
